package com.shdaily.android;

import java.util.ArrayList;

import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.content.Context;
import android.util.Log;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;



public class FeedHandler extends DefaultHandler {
	
	private ArrayList<Article> articles;
	private String WSFeed;
	private String feedURI = "http://www.shanghaidaily.com/webservice/webservice/news.asmx/ArticleListContainContent?";
	private String category;
	private int number;
	private int top;
	private int discount;
	private Article currentArticle;
	private Image currentImage;
	private ArrayList<Image> currentListOfImages;
	private StringBuilder builder;
	private String currentLevel = "ArticleList";
	private EngineDB db;

	
	public FeedHandler(String category, int number, int top, int discount)
	{
		super();
		this.category = category;
		this.number = number;
		this.top = top;
		this.discount = discount;
	}
	
	public ArrayList<Article> getArticles(){
        return this.articles;
    }

	public void characters(char[] ch, int start, int length) throws SAXException 
    {
		super.characters(ch, start, length);
		builder.append(ch, start, length);
    }
	
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        articles = new ArrayList<Article>();
        builder = new StringBuilder();
    }
	
    @Override
    public void startElement(String uri, String localName, String name,
            Attributes attributes) throws SAXException {
        super.startElement(uri, localName, name, attributes);
        if (localName.equalsIgnoreCase("SHDArticle")){
            this.currentArticle = new Article();
            this.currentListOfImages = new ArrayList<Image>();
            this.currentImage = null;
            this.currentLevel = "SHDArticle";
        } else if (localName.equalsIgnoreCase("ArticleImage"))
        {
        	this.currentImage = new Image();
        	this.currentLevel = "ArticleImage";
        }else if (localName.equalsIgnoreCase("ImageList"))
        {
        	this.currentLevel = "ImageList";
        }
    }

	@Override
    public void endElement(String uri, String localName, String name)
            throws SAXException {
        super.endElement(uri, localName, name);
        if (this.currentArticle != null){
            if (localName.equalsIgnoreCase("Title")){
                currentArticle.setTitle(builder.toString());
            } else if (localName.equalsIgnoreCase("ID") && this.currentLevel == "SHDArticle"){
                currentArticle.setId(Integer.parseInt(builder.toString()));
            } else if (localName.equalsIgnoreCase("ID") && this.currentLevel == "ArticleImage"){
                currentImage.setId(Integer.parseInt(builder.toString()));
            } else if (localName.equalsIgnoreCase("Summary")){
                currentArticle.setSummary(builder.toString());
            } else if (localName.equalsIgnoreCase("Content")){
                currentArticle.setBody(builder.toString());
            } else if (localName.equalsIgnoreCase("PublishTime")){
                currentArticle.setDate(builder.toString());
            } else if (localName.equalsIgnoreCase("TimeAgo")){
                currentArticle.setTimeAgo(builder.toString());
            } else if (localName.equalsIgnoreCase("HasPic")){
            	currentArticle.setHasPic(Integer.parseInt(builder.toString()));
            } else if (localName.equalsIgnoreCase("HasHD")){
            	if (builder.toString().equals("0"))
            		currentArticle.setHasHD(false);
            	else currentArticle.setHasHD(true);
            } else if (localName.equalsIgnoreCase("ArticleImage")){
                currentListOfImages.add(currentImage);
                currentImage = null;
                currentLevel = "ImageList";
            } else if (localName.equalsIgnoreCase("ImageList")){
            	currentArticle.setImageList(currentListOfImages);
                currentListOfImages = null;
                currentLevel = "SHDArticle";
            } else if (localName.equalsIgnoreCase("URL")){
            	currentImage.setURL(builder.toString());
            } else if (localName.equalsIgnoreCase("Author")){
            	currentImage.setAuthor(builder.toString());
            } else if (localName.equalsIgnoreCase("Caption")){
            	currentImage.setCaption(builder.toString());
            } else if (localName.equalsIgnoreCase("Size")){
            	currentImage.setCaption(builder.toString());
            } else if (localName.equalsIgnoreCase("SHDArticle")){
            	articles.add(currentArticle);
            	currentArticle = null;
            	currentLevel = "ArticleList";
            }
            builder.setLength(0);
        }
        if (localName.equalsIgnoreCase("ArticleList")) {
            if (articles!=null && articles.size()>0) {
            	if (top == 0) {
            		if (category!=null && !(category.equals(""))){
            			db.refreshArticleList(articles, category);
                		throw new SAXException();
            		}
            	}
            	else {
            		db.refreshTopNewsList(articles);
            		throw new SAXException();
            	}
    		}
        }
    }
	
	public void updateArticles(Context ctx) {
		try {
			db = new EngineDB(ctx);

			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			xr.setContentHandler(this);
			xr.parse(new InputSource(new URL(feedURI 
					+ "category=" + category
					+ "&number=" + number
					+ "&top=" + top
					+ "&discount=" + discount).openStream()));
			
		} catch (IOException e) {
			Log.e("NewsDroid", e.toString());
		} catch (SAXException e) {
			Log.e("NewsDroid", e.toString());
		} catch (ParserConfigurationException e) {
			Log.e("NewsDroid", e.toString());
		} 
	}





}
